<template>
  <div class="searchResult">
    <div class="navbar">
      <Breadcrumb :is-active="true" class="hamburger-container" />
      <div @click="formData.putOne?onSubmit('formData'):''" class="fr " style="margin:26.5px 4% 0 0;">
        <el-switch v-model="formData.lang" false-label='ev' true-label='tw' active-text="EN" inactive-text="繁體">
        </el-switch>
      </div>
      <!-- s -->
    </div>
    <div class="app-container add-page">
      <div class="container-fluid">
        <div class="filter-container searchResultList">
          <el-form ref="formData" :model="formData" :rules="rules" class="event-from">
            <el-row class="h1SearchBar">
              <el-col :sm="5">
                <el-form-item prop="name">
                  <!-- <el-autocomplete
             v-model="athleteData.name"
             :fetch-suggestions="queryAthleteSearchAsync"
             :clearable="true"
             placeholder="Athlete name"
             @select="athleteshandleSelect"
           /> -->
                  <el-input v-model="formData.name" clearable :placeholder="formData.lang?'Name':'運動員姓名'" />
                </el-form-item>
              </el-col>
              <el-col :sm="5">
                <el-form-item prop="date">
                  <!-- <el-input v-model="formData.date" clearable :placeholder="formData.lang?'Year':'年份'" /> -->
                  <!-- <el-select  v-model="formData.resultClass" placeholder="Class" style="width: 260px">
             <el-option v-for="item in CLASS_TYPE" :key="item.value" :label="item.typeName" :value="item.id" />
           </el-select> -->
                  <el-date-picker type="year" v-model="formData.date" value-format='yyyy' format='yyyy' clearable
                    :placeholder="formData.lang?'Year':'年份'"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :sm="5">
                <el-form-item label="" prop="sport">
                  <el-input v-model="formData.sport" clearable :placeholder="formData.lang?'Sport':'運動'" />
                  <!--             <el-select v-model="formData.sport" placeholder="Sport" >
               <el-option v-for="item in SPORTS_TYPE" :key="item.value" :label="item.typeName" :value="item.id"/>
             </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :sm="5">
                <el-form-item label="" prop="eventClasee">
                  <!-- <el-select v-model="formData.types" placeholder="EventClasee" >
            <el-option v-for="item in EVENT_TYPE" :key="item.value" :label="item.eventClasee" :value="item.id" />
          </el-select>-->
                  <el-input v-model="formData.eventClasee" clearable :placeholder="formData.lang?'Category':'比賽分類'"></el-input>
                </el-form-item>
              </el-col>
              <el-col :sm="4">
                <el-form-item label="" prop="putOne">
                  <el-input v-model="formData.putOne" v-show="false" clearable :placeholder="formData.lang?'Sport':'運動'" />
                  <el-button type="button" class="el-button fr el-button--success" :loading="buttonDisable" @click="onSubmit('formData')"><span>{{formData.lang?'Search':'搜索'}}</span></el-button>

                </el-form-item>
              </el-col>
            </el-row>

            <div class="h2SearchBar">
              <el-form-item prop="awards">
                <el-select @change="filterOpen" clearable v-model="formData.competition" :placeholder="formData.lang?'Competition':'賽事'"
                  :remote-method="(q)=>EventMethod(q,'competition')">
                  <el-option v-for="item in opt['competitionList'+(formData.lang?'':'Tc')]" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="level">
                <el-select clearable @change="filterOpen" v-model="formData.level" :placeholder="formData.lang?'Athlete’s Class':'運動員級別'">
                  <el-option v-for="item in opt['levelList'+(formData.lang?'':'Tc')]" :key="item.value" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="athleteClass">
                <el-select clearable @change="filterOpen" v-model="formData.athleteClass" :placeholder="formData.lang?'Project':'項目'">
                  <el-option v-for="item in opt['athleteList'+(formData.lang?'':'Tc')]" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
              <div class="fr">
                <!-- <el-input v-model="listQuery.keyword"  :placeholder="formData.lang?'search':'搜索'" clearable style="width: 200px;"
              @keyup.enter.native="fetchData"> -->
                <!--  <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input> -->
                <a :href="exportLink" @click="()=>!list.resultList.length?$message('No export list'):''">
                  <el-button type="success" icon="el-icon-download"></el-button>
                </a>



                <el-button class="t-center" @click="$refs['formData'].resetFields()" type="reset">
                  {{formData.lang?'reset':'重置'}}
                </el-button>
              </div>

            </div>
          </el-form>
        </div>
        <el-table v-loading="listLoading" :data="list.resultList" :empty-text="formData.lang?'no Data':'沒有數據'"
          element-loading-text="Loading" border fit highlight-current-row stripe @sort-change="sort_change">
          <!-- @sort-change="sort_change" -->
          <el-table-column sortable="custom" min-width="120" prop="competition" :label="formData.lang?'Competition':'比賽名稱'">
            <template slot-scope="scope">
              {{ scope.row.competition || '-'}}
            </template>
          </el-table-column>

          <!-- 項目 -->
          <el-table-column sortable="custom" prop="event" :label="formData.lang?'Event':'項目'">
            <template slot-scope="scope">
              <el-input v-if="scope.row.edit" v-model="scope.row.sceneEventName" />
              <span v-else>
                {{ scope.row.sceneEventName || '-' }}</span>
            </template>
          </el-table-column>
          <!-- 運動 -->
          <el-table-column sortable="custom" prop="sport" :label="formData.lang?'Sport Name':'運動'">
            <template slot-scope="scope">
              <el-select v-if="scope.row.edit" v-model="scope.row.sportName" placeholder="Sport Select" style="min-width: 180px">
                <el-option v-for="item in CLASS_TYPE" :key="item.value" :label="item.typeName" :value="item.id" />
              </el-select>
              <span v-else>{{ scope.row.sportName || '-' }}</span>
            </template>
          </el-table-column>
          <!-- 分類 -->
          <el-table-column sortable="custom" prop="typename" :label="formData.lang?'Category':'分類'">
            <template slot-scope="scope">
              <el-input v-if="scope.row.edit" v-model="scope.row.typeName" />
              <span v-else>
                {{ scope.row.typeName || '-'}}</span>
            </template>
          </el-table-column>
          <!-- 地點 -->

          <el-table-column sortable="custom" prop='location' :label="formData.lang?'Venue':'地點'">
            <template slot-scope="scope">
              <el-input v-if="scope.row.edit" v-model="scope.row.location" />
              <span v-else>
                {{ scope.row.location || '-'}}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column :label="formData.lang?'Location':'地點'"
         prop='activitiesName'
          sortable='custom'
        >
          <template slot-scope="scope">
            {{ scope.row.activitiesName || '-' }}
          </template>
        </el-table-column> -->
          <!-- 日期 -->
          <el-table-column :label="formData.lang?'Date':'日期'" prop='startdate' sortable='custom' width='188'
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ (scope.row.startDate )+ '->'+(scope.row.endDate)  }}
            </template>
          </el-table-column>
          <!-- 運動員 -->
          <el-table-column :label="formData.lang?'Athlete':'運動員'" prop='lastname' min-width="auto" sortable='custom'>
            <template slot-scope="scope">
              {{ scope.row | FilterName(formData.lang?['firstName','lastName']:['tcName']) }}

            </template>
          </el-table-column>
          <!-- 運動員級別  -->
          <el-table-column :label="formData.lang?'Athlete’s Class':'運動員級別'" prop='resultClass' width="120" sortable='custom'>
            <template slot-scope="scope">
              {{ scope.row.resultClass }}
            </template>
          </el-table-column>
          <!-- 成績 -->
          <el-table-column sortable="custom" prop="achievement" :label="formData.lang?'Result':'成績'">
            <template slot-scope="scope">
              <el-input v-if="scope.row.edit" v-model="scope.row.achievement" />
              <span v-else>
                {{ scope.row.achievement }}</span>
            </template>
          </el-table-column>

          <!-- <el-table-column label="Result"  prop='location' sortable='custom'>
          <template slot-scope="scope">
            {{ scope.row.location || '-' }}

             {{ scope.row.tcLocation || '-' }}
          </template>
        </el-table-column> -->
          <!-- 獎項 -->
          <el-table-column sortable="custom" prop="awardname" :label="formData.lang?'Awards':'獎項'">
            <template slot-scope="scope">
              <el-select v-if="scope.row.edit" v-model="formData.awards" placeholder="Awards" style="width: 200px">
                <el-option v-for="item in AWARD_TYPE" :key="item.value" :label="item.typeName" :value="item.id" />
              </el-select>
              <span v-else> {{ scope.row.awardName || '-'}}</span>
            </template>
          </el-table-column>
          <!-- 地区人數 -->
          <el-table-column sortable="custom" min-width="100" prop="countries" :label="formData.lang?'Number of countries ':'參賽地區數'">
            <template slot-scope="scope">
              <el-input v-if="scope.row.edit" v-model="scope.row.countries" />
              <span v-else>
                {{ scope.row.countries || '-'}}</span>
            </template>
          </el-table-column>
          <!-- 参賽人數 -->
          <el-table-column sortable="custom" prop="participants" :label="formData.lang?'Number of participants':'参賽人數'">
            <template slot-scope="scope">
              <el-input v-if="scope.row.edit" v-model="scope.row.participants" />
              <span v-else>
                {{ scope.row.participants }}</span>
            </template>
          </el-table-column>
          <!--  排名-->
          <el-table-column sortable="custom" prop="ranking" :label="formData.lang?'Ranking':'排名'">
            <template slot-scope="scope">
              <el-input v-if="scope.row.edit" v-model="scope.row.ranking" />
              <span v-else>
                {{ scope.row.ranking }}</span>
            </template>
          </el-table-column>

          <!-- <el-table-column fixed="right" label="" width="100">
         <template slot-scope="scope">
           <EditDel :row="scope.row" @confirmEdit="confirmEdit" @del="del" />
         </template>
       </el-table-column> -->
        </el-table>
        <el-pagination layout="sizes, prev, pager, next" :page-size="listQuery.size" :current-page="listQuery.page"
          :total="listQuery.total" class="pagination-container" :page-sizes="[25, 50, 100]" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>

</template>

<script>
  // import { getInterList } from '@/api/home'
  import {
    EventAthleteOpen,
    modifyEventAthlete,
    delEventAthlete,
    getEventAthlete,
    getEventScene
  } from '@/api/event'
  import Breadcrumb from '@/components/Breadcrumb'
  import {
    queryAthletesList,
    getBelongingTypes
  } from '@/api/setting'
  import {
    getTypeName
  } from '@/utils'
  import Vue from 'vue'
  // import Element from 'element-ui'
  import en from 'element-ui/lib/locale/lang/en'
  import cn from 'element-ui/lib/locale/lang/zh-CN'
  // Vue.use(Element, { locale })
  export default {
    data() {
      var checkAge = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('年齡不能為空'))
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('請輸入數字值'))
          } else {
            if (value < 18) {
              callback(new Error('必须年滿18嵗'))
            } else {
              callback()
            }
          }
        }, 1000)
      }
      return {
        listLoading: false,
        buttonDisable: false,
        list: {
          matchEvent: {},
          scene: {},
          resultList: []
        },
        listQuery: {
          page: 1,
          total: 1,
          sorting: 0,
          column: '',
          size: 20
        },
        listLoad0ing: true,
        link: '/event/addEdit',
        AWARD_TYPE: [],
        CLASS_TYPE: [],
        SPORTS_TYPE: [],
        EVENT_TYPE: [],
        restaurants: [],
        athleteData: {
          name: '',
          id: '',
          list: []
        },
        EventAthleteOpen,

        formData: {
          putOne: '',
          date: '',
          sport: '',
          athleteClass:'',
          eventClasee: '',
          sorting: 0,
          column: '',
          size: 1,
          lang: 'en',
          name: '',
          competition: '',
          level: '',

        },
        opt: {

        },
        lang: false,
        rules: {
          sport: [{
            required: false,
            message: 'Sport cannot be empty'
          }],
          date: [{
            required: false,
            message: 'Date cannot be empty',
            trigger: 'blur'
          }],
          name: [{
            required: false,
            message: 'Name cannot be empty',
            trigger: 'blur'
          }],
          eventClasee: [{
            required: false,
            message: 'EventClasee cannot be empty',
            trigger: 'blur'
          }],
          putOne: [{
            required: true,
            message: 'Please input Sport or Date or Name',
            trigger: 'blur'
          }],
          // ranking: [
          //     { required: false, message: 'Ranking cannot be empty', trigger: 'blur' }
          // ],
          // awards: [
          //     { required: true, message: 'Please select', trigger: ['change', 'blur'] }
          // ],
          // remark: [
          //     { required: false, message: 'Please input', trigger: 'blur' }
          // ],
          // resultTeam: [
          //     { required: true, message: 'Team cannot be empty', trigger: 'blur' }
          // ]
        }
      }
    },
    components: {
      Breadcrumb
    },
    watch: {
      // ['formData.competition'](val){
      //   this.filterOpen()
      // },
      // // ['formData.year'](val){
      // //   this.formData.date = val.getFullYear()
      // // },
      // ['formData.level'](val){
      //   this.filterOpen()
      // },
      // ['formData.athleteClass'](val){
      //   this.filterOpen()
      // },
       ['formData.name'](val) {
         this.formData.putOne = val
       },
       ['formData.eventClasee'](val) {
         this.formData.putOne = val
       },
       ['formData.date'](val) {
         this.formData.putOne = val
       },

      ['formData.lang'](val) {

        this.$route.meta.title = val ? 'Results' : '成績搜索'
        this.formData.athleteClass = ''
        this.formData.level = ''
        this.formData.eventClasee = ''
        //Vue.use( { locale:!val?en:cn })
        //val?Vue.locale('zh-cn', cn):Vue.locale('en', en)
      }
    },
    created() {
      // this.$store.dispatch('clogRole/clogCompetitionList')
      // this.$store.dispatch('clogRole/clogEventList',)
      // this.$store.dispatch('clogRole/clogGradeList')
      const query = this.$route.query
      if (query.id) {
        this.formData.sceneId = query.id
      }
    },
    computed: {
      exportLink() {
        //var Course = this.activeName==='Course'
        var params = '?lang=' + (!this.formData.lang ? 'tw' : 'en') +
          (this.formData.name ? '&name=' + this.formData.name : '') +
          (this.formData.date ? '&date=' + this.formData.date : '') +
          (this.formData.sport ? '&sport=' + this.formData.sport : '') +
          (this.formData.eventClasee ? '&eventClasee=' + this.formData.eventClasee : '') +
          (this.formData.competition ? '&competition=' + this.formData.competition : '') +
          (this.formData.level ? '&level=' + this.formData.level : '') +
          (this.formData.athleteClass ? '&athleteClass=' + this.formData.athleteClass : '')
        let url;
        if (!this.list.resultList.length) {
          url = 'javascript:void(0)'
          // this.$message('No export list')
        } else {
          url = process.env.VUE_APP_BASE_API + '/export/open/' + 'event' + '/xls' + params
        }

        return url
      },
    },
    methods: {
      paramsStr() {
        let lang = this.formData.lang ? 'en' : 'tw'
        let {
          name,
          date,
          sport,
          eventClasee,
          competition,
          level,
          athleteClass
        } = this.formData
        console.log("project", this.formData)
        let {
          sorting,
          column,
          size,
          page
        } = this.listQuery
        let params = {
          lang,
          name,
          date,
          sport,
          eventClasee,
          sorting,
          column,
          competition,
          level,
          athleteClass,
          size,
          page
        }

        return params
      },
      filterOpen() {
        let params = this.paramsStr()
        //

        this.$ajax({
          url: '/open/event/query_filter',
          params
        }).then((response) => {
          let data = response.result
          if (response.status === 0) {
            this.list.resultList = data.list
            this.listQuery.total = data.total ? data.total : this.listQuery.total
            this.formData.putOne = ''
            //this.listQuery.page = data.totalPage
            //this.listQuery.exportToken = data.exportToken
            // this.$message({
            //     type: 'success',
            //     message: response.msg
            // })
          }
        }).catch((err) => {

        })

      },
      onSubmit(formName) {


        // debugger
        this.$refs[formName].validate((valid) => {

          if (valid) {
            this._buttonDisable(this, 'buttonDisable')

            const list = this.list

            EventAthleteOpen(this.paramsStr()).then(response => {
              this._buttonDisable(this, 'buttonDisable', false)
              // eslint-disable-next-line no-unused-vars
              const data = response.result
              if (response.status === 0) {
                this.opt = data
                list.resultList = data.list
                this.listQuery.total = data.total ? data.total : this.listQuery.total
                // this.formData.putOne = ''
                this.formData.competition = ''
                this.formData.athleteClass = ''
                this.formData.level = ''
                this.formData
                //this.listQuery.page = data.totalPage
                //this.listQuery.exportToken = data.exportToken
                // this.$message({
                //     type: 'success',
                //     message: response.msg
                // })
              }
            })
          }
        })
      },

      EventMethod(query, Event) {

        let {
          [Event]: opt, [Event + 'List']: optList, [Event + 'Loading']: optLoading
        } = this.opt
        if (query !== '' && optList) {
          setTimeout(() => {
            optLoading = false;
            opt = optList.Length ? optList.filter(item => {
              return item.label.toLowerCase()
                .indexOf(query.toLowerCase()) > -1;
            }) : [];
          }, 200);
        } else {
          opt = [];
        }
      },
      sort_change(column) {
        this.listQuery.page = 1
        if (column.prop && column.order) {

          this.listQuery.sorting = column.order ? column.order === 'ascending' ? 0 : 1 : !this.listQuery.sorting ? 1 :
            0;
          console.log('sorting', column.order === 'ascending', this.listQuery.sorting)
          this.listQuery.column = column.prop
          this.formData.sorting = this.listQuery.sorting
          this.formData.column = column.prop
          this.onSubmit('formData')
        }
      },
      fetchData() {
        this.getEventAthlete()

        getBelongingTypes({
          belonging: 'EVENT'
        }).then(response => {
          const data = response.result
          this.AWARD_TYPE = data.AWARD_TYPE
          // this.CLASS_TYPE = data.CLASS_TYPE
          this.EVENT_TYPE = data.CLASS_TYPE
          //this.EVENT_COUNTRY = data.EVENT_COUNTRY
          // this.AWARD_TYPE = data.AWARD_TYPE
        })
        getBelongingTypes({
          belonging: 'MISCELLANEOUS'
        }).then(response => {
          const data = response.result
          this.SPORTS_TYPE = data.SPORTS_TYPE
        })
      },
      getEventAthlete(formData) {
        getEventAthlete({
          sceneId: this.formData.sceneId,
          keyword: this.listQuery.keyword,
          page: this.listQuery.page,
          sorting: this.listQuery.sorting,
          column: this.listQuery.column,
          size: this.listQuery.size
        }).then(response => {
          this.list = response.result
          this.listLoading = false
        })
      },
      queryAthleteSearchAsync(queryString, cb) {
        if (queryString === '') {
          cb([])
          return false
        }
        var restaurants = this.restaurants
        queryAthletesList({
          name: queryString
        }).then(response => {
          // var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants
          var results = [];
          var data = response.result

          for (var i in data) {
            this.isvalidator = queryString.indexOf(data[i].lastName + data[i].firstName) > -1
            results.push({
              value: data[i].lastName + ' ' + data[i].firstName,
              name: data[i].lastName + ' ' + data[i].firstName + ' ' + data[i].hkId,
              id: data[i].userId
            })
          }
          clearTimeout(this.timeout)
          this.timeout = setTimeout(() => {
            cb(results)
          }, 200 * Math.random())
        })
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      athleteshandleSelect(item) {
        this.athleteData.name = item.name
        this.athleteData.id = item.id
        this.formData.userId = item.id
      },
      confirmEdit(row) {
        if (row.loading) return false
        this._buttonDisable(row.loading)
        const list = this.list.sceneList
        const {
          id,
          sceneId,
          userId,
          achievement,
          resultContent,
          resultClass,
          remark,
          ranking,
          awards,
          resultTeam
        } = row
        // this._buttonDisable(row.loading)
        addEventAthlete({
          id,
          sceneId,
          userId,
          achievement,
          resultContent,
          resultClass,
          remark,
          ranking,
          awards,
          resultTeam
        }).then(response => {
          // this._buttonDisable(this.buttonDisable)
          const statu = response.status === 0
          this._buttonDisable(row.loading, true)
          if (statu) {
            row = response.result
            for (var i in list) {
              if (list[i].id === row.id) {
                list[i].edit = false
              }
            }
          }
          this.$message({
            message: response.msg,
            type: statu ? 'success' : 'warning'
          })
        })
      },
      del(id) {
        this.$confirm('This action will permanently delete this item. Do you want to continue?', 'Tips', {
          confirmButtonText: 'Yes',
          cancelButtonText: 'No',
          type: 'warning'
        }).then(() => {
          delEventAthlete({
            id: id
          }).then(response => {
            if (response.status === 0) {
              this.$message({
                type: 'success',
                message: response.msg
              })
              this.fetchData()
            }
          })
        }).catch(() => {

        })
      },
      // pageSize变化事件
      handleSizeChange(val) {
        this.listQuery.size = val
        //debugger
        this.onSubmit('formData')
      },
      // pageNum变化事件
      handleCurrentChange(page) {
        this.listQuery.page = page
        //debugger
        // this.trainScheduleList(page, this.activeName)
        this.onSubmit('formData')
      },
      sportMedicineFormatLink(row, column) {
        return row.row.id = 1
      }
    }
  }
</script>
<style lang="scss">
  .searchResult {
    .navbar {
      .el-breadcrumb {
        background: #00468C;
        margin: 5px 0;
        padding: 5px 15px;
        min-width: 65%;
      }

      background: #fff;
      -webkit-box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
      box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
    }


    .el-form {
      .h1SearchBar {
        .el-form-item {
          width: 100%;

          div,
          input {
            width: 100%;
            display: block;
          }
        }
      }

    }

    .event-from {
      text-align: left;
    }

    .event-from .el-input {
      margin-right: 5px;
    }

    .event-from .el-form-item {
      margin-right: 0px;
      display: inline-block;
    }

    .event-from .el-input input {
      border-radius: 0;
    }

    .at span {
      color: #586982;
      margin-right: 20px;
    }
  }
</style>
